package com.chinameyer.workorders.controller;

import com.chinameyer.workorders.bean.MeyerUser;
import com.chinameyer.workorders.dto.user.ChangePasswordDTO;
import com.chinameyer.workorders.dto.user.CreateUserDTO;
import com.chinameyer.workorders.dto.user.LoginDTO;
import com.chinameyer.workorders.dto.user.UpdateUserDTO;
import com.chinameyer.workorders.service.UserService;
import com.chinameyer.workorders.utils.FileUtils;
import com.chinameyer.workorders.vo.LoginVO;
import com.chinameyer.workorders.vo.UserVO;
import com.xinmachong.response.ApiResponse;
import com.xinmachong.response.ApiResponseWithPage;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * @Author meyer@HongYe
 */
@RestController
@RequestMapping("/v1/user")
@Validated
@CrossOrigin
public class UserController {

    @Resource
    private UserService userService;

    @Value("${mydefine.address}")
    private String address;
    @Value("${mydefine.out-port}")
    private String port;
    @Value("${mydefine.images.path}")
    private String imagesPath;


    @PostMapping("/login")
    public ApiResponse login(@RequestBody @Validated LoginDTO loginDTO) {
        String salt;
        try {
            salt = this.userService.getSaltByAccount(loginDTO);
        } catch (Exception e) {
            return new ApiResponse(400,"账号不存在",0);
        }
        String password = new SimpleHash("MD5",loginDTO.getPassword(),salt,1).toHex();
        String realPassword = this.userService.getPasswordByAccount(loginDTO);
        if(StringUtils.isEmpty(realPassword)){
            return new ApiResponse(400,"用户名错误",0);
        } else if (!realPassword.equals(password)) {
            return new ApiResponse(400, "密码错误", 0);
        } else {
            LoginVO loginVO = this.userService.getUserMsg(loginDTO);
            return new ApiResponse(200,"success",loginVO);
        }
    }


    @PostMapping("/changePassword")
    public ApiResponse changePassword(HttpServletRequest request, @RequestBody @Validated ChangePasswordDTO changePasswordDTO) {
        if (!changePasswordDTO.getNewPassword().equals(changePasswordDTO.getConfirmPassword())) {
            return new ApiResponse(400,"新密码和确认密码输入不一致",0);
        }
        try {
            this.userService.changePassword(request, changePasswordDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"密码修改失败",0);
        }
    }


    @PostMapping("/add")
    public ApiResponse add(@RequestBody @Validated CreateUserDTO createUserDTO) {
        boolean isExistStaffNo = this.userService.checkStaffNoIsExist(createUserDTO);
        if (isExistStaffNo) {
            return new ApiResponse(400,"工号已存在，请勿重复添加",0);
        }
        try {
            this.userService.addUser(createUserDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"用户添加失败",0);
        }
    }


    @DeleteMapping("/delete")
    public ApiResponse delete(@RequestParam(value = "userId") Integer userId) {
        try {
            this.userService.deleteUser(userId);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"用户删除失败",0);
        }
    }


    @PostMapping("/edit")
    public ApiResponse edit(@RequestBody @Validated UpdateUserDTO updateUserDTO) {
        boolean isExistStaffNo = this.userService.checkStaffNoIsExistExpectItself(updateUserDTO);
        if (isExistStaffNo) {
            return new ApiResponse(400,"工号已存在，请确认信息后再更新",0);
        }
        try {
            this.userService.editUser(updateUserDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"用户更新失败",0);
        }
    }


    @GetMapping("/getAll")
    public ApiResponseWithPage getAll(@RequestParam(name = "count", required = false, defaultValue = "10")
                              @Min(value = 1, message = "分页数量必须为正整数") Integer count,
                              @RequestParam(name = "page", required = false, defaultValue = "1")
                              @Min(value = 0, message = "分页必须为正整数") Integer page) {
        List<UserVO> userList = this.userService.getAllUsers(count,page - 1);
        int total = this.userService.getAllUsersTotal();
        return new ApiResponseWithPage(200,"success",userList,total);
    }


    @PostMapping("/uploadImages")
    public ApiResponse uploadImages(@RequestParam("file") MultipartFile file) {
        String name = file.getOriginalFilename();
        String newFileName = FileUtils.upload(file, imagesPath, name);
        if(newFileName != null){
            return new ApiResponse(200,"success",address+":"+port+"/images/"+newFileName);
        }
        return new ApiResponse(400,"上传失败",0);
    }
}
